import axios from "axios";
import { Message } from "iview";
import router from "@/router";

const service = axios.create({
  timeout: 10000 * 3 // 请求超时时间
});

service.interceptors.request.use(async config => {
  return config;
});

service.interceptors.response.use(
  function(res) {
    if (res.data.head.errCode == -200) {
      onMessage("warning", "请重新登录");
      router.replace({
        path: "/login"
      });
      throw res;
    }
    if (res.data.head.errCode !== 200) {
      onMessage("warning", res.data.head.errMsg);
      throw res;
    }
    return res;
  },
  function(error) {
    if (!error.response) {
      onMessage("error", "服务器请求超时，请刷新后重试！");
      return Promise.reject(error);
    }
    const { status, data } = error.response;
    if (data) {
      onMessage("error", data.message || "系统异常");
    }
    return Promise.reject(status);
  }
);
export default service;

function onMessage(type, message) {
  message = message + "";
  message = message.split(":")[0];
  Message[type](message);
}
